import {IMapBusiness} from "../imap-business";
import {MapApi} from "../../../model/map/MapApi";
import {Point} from "../../../model/map/Point";
import {ViewportOptions} from "../../../model/map/ViewportOptions";

export class MapPageBusiness implements IMapBusiness{

    /**
     * 添加圆形覆盖物
     * @param {Point} point
     * @param {number} radius
     * @param {MapApi} mapApi
     * @returns {mapApi._mapApi.Circle}
     */
    addCircle(point:Point,radius:number=2000,mapApi:MapApi){

        if(!mapApi || !mapApi._mapApi)return;

        // 百度地图API功能
        let circle = new mapApi._mapApi.Circle(point, radius, {
            fillColor: "#35ac63",
            strokeWeight: 1,
            fillOpacity: 0.15,
            strokeOpacity: 0.15
        });
        circle.disableMassClear();      //不统一清理
        if(!mapApi._mapInstance)return;
        mapApi._mapInstance.addOverlay(circle);
        return circle;
    }

    /**
     * 添加标注
     * @param {Point} point
     * @param {MapApi} mapApi
     * @param {string} iconPath
     * @param {string} enableDragging
     * @param {number} zindex
     * @returns {any}
     */
    addMarkerByPoint(point:Point,mapApi:MapApi,iconPath:string="",enableDragging:boolean=false,zindex?:number){
        let bmapApi = mapApi._mapApi;
        if (!mapApi || !bmapApi) return null;
        let mPoint = new bmapApi.Point(point.lng, point.lat);
        let myIcon = new bmapApi.Icon(iconPath ? iconPath : "./assets/images/map/icon_destination.png", new bmapApi.Size(34, 34));
        let marker = new bmapApi.Marker(mPoint, {
            offset: new bmapApi.Size(0,-3),
            icon: myIcon,
            enableDragging: enableDragging,
            title: ""
        });
        if(zindex){
            marker.setZIndex(zindex);
        }
        marker.disableMassClear();//不统一清理
        if(!mapApi._mapInstance)return;
        mapApi._mapInstance.addOverlay(marker);
        return marker;
    }

    /**
     * 为marker添加label
     * @param {MapApi} mapApi
     * @param marker
     * @param point
     * @param w 宽度
     * @param h 高度
     * @param {string} content
     * @param {boolean} isMore
     * @returns {bmapApi.Label}
     */
    addLabelForMarker(mapApi:MapApi, marker, point, w,h,content:string = null,isMore:boolean) {
        let result = this.formatNameLabel(isMore,content);
        let bmapApi = mapApi._mapApi;
        let offset = new bmapApi.Size(-14, -4);
        let labelgg = new bmapApi.Label(
            result.name?result.name:`${point.lng},${point.lat}`,
            {
                offset: offset
            }
        );
        labelgg.setStyle({
            border:'1px solid #959595',
            display:'inline-block',
            fontSize:'14px',
            padding:'1px 0',
            color:'#333',
            background:'#fff',
            borderRadius:'12px',
            marginTop:'40px',
            width:'64px',
            textAlign:'center',
            zIndex:'-1'
        });
        if(!marker)return;
        marker.setLabel(labelgg);
        return labelgg;
    }

    /**
     * 客户名字处理
     * @param {boolean} isMore
     * @param {string} name
     * @returns {{left: number; name: string}}
     */
    formatNameLabel(isMore:boolean,name:string){
        let result = {
            left:-6,
            name:name
        };

        if(name&&name.length > 4){
            name = name.substr(0,3) + '...';
            if(isMore){
                result.name = name.substr(0,2)+'...<span style="color: #999">等</span>';
            }else {
                result.name = name;
            }
        }

        if(name&&(name.length == 2 || name.length == 3)){
            if(isMore){
                result.name = name.substr(0,3)+'<span style="color: #999">等</span>';
            }
        }

        return result;
    }

    //删除覆盖物
    removeOverlay(mapApi:MapApi,overlay:any){
        if(mapApi && mapApi._mapInstance && overlay){
            mapApi._mapInstance.removeOverlay(overlay);
        }
    }

    //添加覆盖物
    addOverlay(mapApi: MapApi, overlay: any) {
        if(!mapApi._mapInstance)return;
        mapApi._mapInstance.addOverlay(overlay);
    }

    //平滑移动地图中心点
    panTo(p:Point,mapApi: MapApi){
        let bPoint = new mapApi._mapApi.Point(p.lng,p.lat);
        mapApi._mapInstance.panTo(bPoint);
    }

    /**
     * 设置地图缩放级别
     * @param {number} zoom 地图缩放级别
     * @param {MapApi} mapApi
     */
    setZoom(zoom:number,mapApi:MapApi){
        if(!mapApi || !mapApi._mapInstance)return;
        mapApi._mapInstance.setZoom(zoom);
    }

    /**
     *设置最佳视图
     */
    setViewport(points:Array<Point>,viewportOptions: ViewportOptions = null,mapApi:MapApi){
        viewportOptions = viewportOptions || new ViewportOptions([5,5,5,5]);

        let poies = [];
        points.forEach(poi => {
            let p = new mapApi._mapApi.Point(poi.lng, poi.lat);
            poies.push(p);
        });
        if(poies.length){
            mapApi._mapInstance.setViewport(poies,viewportOptions);
        }
    }

    //生成驾车路线
    generateDriveRoute(p1: Point, p2: Point,mapApi:MapApi) {
        let startPoint = new mapApi._mapApi.Point(p1.lng,p1.lat);
        let endPoint = new mapApi._mapApi.Point(p2.lng,p2.lat);
        // mapApi._mapInstance.clearOverlays();
        let driving = new mapApi._mapApi.DrivingRoute(mapApi._mapInstance,
            {
                renderOptions:{
                    map: mapApi._mapInstance,
                    autoViewport: true
                }
            });
        driving.search(startPoint, endPoint);
    }

    //搜索建议（自动完成）
    autoCompeleted(mapApi: MapApi, inputHtmlEle, callBack) {
        let options = {
            input:inputHtmlEle
        };
        let ac = new mapApi._mapApi.Autocomplete(options);
        ac.addEventListener("onconfirm", function(e) {
            let _value = e.item.value;
            let address = `${_value.province}${_value.city}${_value.district}${_value.street}${_value.business}`;
            callBack(address);
        });
        return ac;
    }

    //目的地搜索
    searchDestination(addr: string, mapApi: MapApi, cb) {
        if(!mapApi || !mapApi._mapInstance)return;
        let center = mapApi._mapInstance.getCenter();
        let local = new mapApi._mapApi.LocalSearch(center,{
            onSearchComplete:(r) => {
                let localResultPoi = {
                    point:{
                        lng:0,
                        lat:0
                    }
                };
                let totalCurrentPage = r.getCurrentNumPois();
                if(totalCurrentPage){
                    localResultPoi = r.getPoi(0);
                    // this.destinationed(localResultPoi.point,this.mapApi._mapApi,this.mapApi._mapInstance);
                    // this.mapCenter.marker = MapProvider.addMarkerByPoint(
                    //     localResultPoi.point,
                    //     this.mapApi._mapApi,
                    //     this.mapApi._mapInstance,
                    //     null,
                    //     false
                    // );
                    // this.mapApi._mapInstance.panTo(localResultPoi.point);
                }
                let searchResult = {
                    point:{
                        lng:localResultPoi.point.lng,
                        lat:localResultPoi.point.lat
                    }
                };
                cb(searchResult);
            }
        });
        local.search(addr);
    }

    //获取地图中心点地址
    getMapCenterAddress(mapApi:MapApi,callback){
        let center = mapApi._mapInstance.getCenter();
        this.getAddressByPoint(mapApi,center,addrCom => {
            if(callback){
                callback(addrCom);
            }
        });
    }

    //获取坐标对应的地址
    getAddressByPoint(mapApi:MapApi,point,callback){
        let geoc = new mapApi._mapApi.Geocoder();
        let location = new mapApi._mapApi.Point(point.lng,point.lat);
        geoc.getLocation(location, function(rs){
            let addComp = rs.address;
            if(callback){
                callback(addComp);
            }
        });
    }

    /**
     * 获取地址对应的经纬度
     * @param {MapApi} mapApi 地图api
     * @param {string} address 要搜索的地址
     * @param {string} city 限制搜索的城市范围
     * @param callback
     */
    getLatlngByAdd(mapApi:MapApi, address: string,city:string, callback){
        let geo = new mapApi._mapApi.Geocoder();
        this.getMapCenterAddress(mapApi,addrCom => {
            if(addrCom && addrCom.city){
                city = addrCom.city;
            }
            geo.getPoint(address, function (point) {
                if (callback) {
                    callback(point);
                }
            },city);

        });
    }

    /**
     * 转换标准经纬度为地图经纬度
     * @param {MapApi} mapApi
     * @param {number} lat
     * @param {number} lng
     * @param cb
     */
    convertLatLng(mapApi:MapApi,lat:number,lng:number,cb){
        let ggPoint = new mapApi._mapApi.Point(lng,lat);
        let convertor = new mapApi._mapApi.Convertor();
        convertor.translate([ggPoint], 1, 5, data => {
            cb(data);
        });
    }

    /**
     * 设置地图中心位置和缩放级别
     * @param {MapApi} mapApi
     * @param {Point} center
     * @param {number} zoom
     */
    centerAndZoom(mapApi:MapApi,center:Point,zoom:number){
        let point = new mapApi._mapApi.Point(center.lng,center.lat);
        mapApi._mapInstance.centerAndZoom(point,zoom);
    }


    /**
     * 添加缩放控件
     * @param {MapApi} mapApi
     */
    addZoomControl(mapApi:MapApi){
        let BMap = mapApi._mapApi;
        let map = mapApi._mapInstance;

        let topRightNavigation = new BMap.NavigationControl({
            anchor: window['BMAP_ANCHOR_TOP_RIGHT'],
            type: window['BMAP_NAVIGATION_CONTROL_SMALL']
        });
        map.addControl(topRightNavigation);
    }
}
